import { sys } from "cc"
import { ENUM_GAME_STATUS } from "../Enum"

const KEY_STORAGE = 'CC3_SCREWLEVEL_KEY'
const COUNT_DOWN = 160
const COUNT_DOWN_SOUND = 5

export type ICallBack = {
    status: boolean,
    data: any,
    msg: string
}

export type IUser = {
    openid: string,
    nickname: string,
    gender: number,
    avatar: string
}

export class DataMgr {
    private static _ins: any = null

    static getIns<T>(): T {
        if (this._ins === null) {
            this._ins = new this()
        }
        return this._ins
    }

    static get ins() {
        return this.getIns<DataMgr>()
    }

    loadingRange: number = 0
    isMusic: boolean = true
    isSound: boolean = true
    gameStatus: ENUM_GAME_STATUS = ENUM_GAME_STATUS.UNACTIVE
    currentLevel: number = 1
    hardLevel: number = 8
    user: IUser = null
    total: number = 0
    cleared: number = 0
    isHard: boolean = false
    countDown: number = COUNT_DOWN
    countDownSound: number = COUNT_DOWN_SOUND
    level: number = -1
    isResetSkillBtn: boolean = false

    reset() {
        this.gameStatus = ENUM_GAME_STATUS.UNACTIVE
        this.total = 0
        this.cleared = 0
        this.countDown = COUNT_DOWN
    }

    restore() {
        const storage = sys.localStorage.getItem(KEY_STORAGE) as any
        try {
            const data = JSON.parse(storage)
            this.isMusic = data?.isMusic == false ? false : true
            this.isSound = data?.isSound == false ? false : true
            this.currentLevel = typeof data.currentLevel == 'number' ? data.currentLevel : 1
            this.user = data?.user || null
        } catch {
            this.isMusic = true
            this.isSound = true
            this.currentLevel = 1
            this.user = null
        }
    }

    save() {
        sys.localStorage.setItem(KEY_STORAGE, JSON.stringify({
            isMusic: this.isMusic,
            isSound: this.isSound,
            currentLevel: this.currentLevel,
            user: this.user
        }))
    }
}


